using Autofac;
using Autofac.Extensions.DependencyInjection;
using CoreManager.API.Configuration;
using CoreManager.Core.Extensions;
using CoreManager.Core.Logging;
using CoreManager.Repository.DbContext;
using CoreManager.Models.Mappings;
using CoreManager.AI.Configuration;
using CoreManager.MessageQueue.Extensions;
using CoreManager.Elasticsearch.Extensions;
using Microsoft.EntityFrameworkCore;
using Serilog;

var builder = WebApplication.CreateBuilder(args);

// 配置Serilog - 替换默认日志提供者
Log.Logger = SerilogConfiguration
    .ConfigureSerilog(builder.Configuration, builder.Environment)
    .CreateLogger();

// 清除默认日志提供者，只使用Serilog
builder.Logging.ClearProviders();
builder.Host.UseSerilog(Log.Logger, dispose: true);

// 配置Autofac
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
builder.Host.ConfigureContainer<ContainerBuilder>(containerBuilder =>
{
    // 注册主模块
    containerBuilder.RegisterModule(new DependencyInjectionModule(builder.Configuration));
    
    // 注册条件模块
    containerBuilder.RegisterModule(new ConditionalModule(builder.Configuration));
    
    // 注册环境特定模块
    containerBuilder.RegisterModule(new EnvironmentModule(builder.Environment.EnvironmentName));
});

// 配置JSON序列化选项（包含控制器配置）
builder.Services.ConfigureJsonOptions();

// 添加HttpContextAccessor
builder.Services.AddHttpContextAccessor();

// 添加AutoMapper配置
builder.Services.AddAutoMapper(typeof(MenuMappingProfile), typeof(RoleMappingProfile));

// 添加缓存服务
builder.Services.AddCacheService(builder.Configuration);

// 配置EF Core（使用连接池）
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection")?? "";
// 配置连接字符串，添加连接池参数
var connectionStringBuilder = new MySqlConnector.MySqlConnectionStringBuilder(connectionString)
{
    // 连接池配置
    Pooling = true,                    // 启用连接池
    MinimumPoolSize = 5,               // 最小连接池大小
    MaximumPoolSize = 100,             // 最大连接池大小
    ConnectionLifeTime = 300,          // 连接生命周期（秒）
    ConnectionIdleTimeout = 180,       // 空闲连接超时时间（秒）
    
    // 性能优化
    ConnectionTimeout = 30,            // 连接超时（秒）
    DefaultCommandTimeout = 30,        // 命令超时（秒）
    
    // 其他优化
    AllowUserVariables = true,
    UseAffectedRows = false
};

// 打印数据库连接信息
Log.Information("数据库配置 -> MySQL: {Server}:{Port}/{Database} (用户: {User}) | 连接池: Min={Min}, Max={Max}, Timeout={Timeout}s", 
    connectionStringBuilder.Server, 
    connectionStringBuilder.Port, 
    connectionStringBuilder.Database, 
    connectionStringBuilder.UserID,
    connectionStringBuilder.MinimumPoolSize,
    connectionStringBuilder.MaximumPoolSize,
    connectionStringBuilder.ConnectionTimeout);

// 使用 AddDbContextPool 提高性能（推荐用于高并发场景）
builder.Services.AddDbContextPool<CoreManagerDbContext>(options =>
{
    options.UseMySql(
        connectionStringBuilder.ConnectionString, 
        ServerVersion.AutoDetect(connectionStringBuilder.ConnectionString),
        mySqlOptions =>
        {
            // 启用重试机制（处理瞬时故障）
            mySqlOptions.EnableRetryOnFailure(
                maxRetryCount: 3,
                maxRetryDelay: TimeSpan.FromSeconds(5),
                errorNumbersToAdd: null
            );
            
            // 命令超时设置
            mySqlOptions.CommandTimeout(30);
            
            // 启用字符串拆分查询优化
            mySqlOptions.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery);
        }
    );
    
    // 查询优化
    options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTrackingWithIdentityResolution);
    
    // 开发环境启用敏感数据记录
    if (builder.Environment.IsDevelopment())
    {
        options.EnableSensitiveDataLogging();
        options.EnableDetailedErrors();
    }
    else
    {
        // 生产环境优化
        options.EnableServiceProviderCaching();
    }
}, poolSize: 128); // DbContext 池大小

// 配置自定义数据库日志
builder.Services.ConfigureDatabaseLogging();

// 添加自定义服务
builder.Services
    .AddJwtAuthentication(builder.Configuration)
    .AddSwaggerDocumentation()
    .AddCorsPolicy(builder.Configuration)
    .AddRedisCache(builder.Configuration)
    .AddAIServices(builder.Configuration);
    //.AddKafka(builder.Configuration)
    //.AddElasticsearch(builder.Configuration);

var app = builder.Build();

try
{
    Log.Information("正在启动 CoreManager API...");

    // 全局异常处理中间件（必须在所有中间件之前注册）
    app.UseMiddleware<CoreManager.API.Middleware.GlobalExceptionHandlerMiddleware>();

    // 配置中间件管道
    app.ConfigureMiddlewarePipeline(app.Environment);

    // 配置Swagger文档
    app.UseSwaggerDocumentation(app.Environment);

    // 初始化数据库
    using (var scope = app.Services.CreateScope())
    {
        var context = scope.ServiceProvider.GetRequiredService<CoreManagerDbContext>();
        await context.InitializeDatabaseAsync();
    }

    // 映射控制器
    app.MapControllers();

    Log.Information("CoreManager API 启动成功，监听端口: {Urls}", string.Join(", ", app.Urls));
    
    app.Run();
}
catch (Exception ex)
{
    Log.Fatal(ex, "CoreManager API 启动失败");
    throw;
}
finally
{
    Log.CloseAndFlush();
}